package com.hxs.colorfultest2.controller;


import com.hxs.colorfultest2.domain.Factory;
import com.hxs.colorfultest2.domain.Theme;
import com.hxs.colorfultest2.domain.User;
import com.hxs.colorfultest2.service.FactoryService;
import com.hxs.colorfultest2.service.ThemeService;
import jdk.management.resource.ThrottledMeter;
import org.apache.tomcat.util.codec.binary.Base64;
import org.apache.tomcat.util.http.fileupload.FileItem;

import org.apache.tomcat.util.http.fileupload.RequestContext;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.util.Streams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.context.Theme;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;


@Controller
public class ThemeManagerController {
    @Autowired
    ThemeService themeService;

    @Autowired
    FactoryService factoryService;


    //String themeName = null;

    /*获取所有主题进行分页*/
    @RequestMapping("/theme")
    public Model getAllUser(Model model, @RequestParam(value = "curPage", required = false) Integer curPage) {
        int pageSize = 10;

        /*当前页*/
        if (curPage == null) {
            curPage = 1;
        }
        int totalRows = themeService.getThemeByTotal();
        int totalPages = totalRows / pageSize;
        int left = totalRows % pageSize;
        if (left > 0) {
            totalPages = totalPages + 1;
        }

        Map<String, Object> paramMap = new ConcurrentHashMap<>();
        /*计算当前页*/
        int start = (curPage - 1) * pageSize;
        paramMap.put("start", start);
        paramMap.put("pageSize", pageSize);

        List<Theme> themeList = themeService.getThemeByPage(paramMap);
        model.addAttribute("themeList", themeList);
        model.addAttribute("totalRows", totalRows);
        model.addAttribute("curPage", curPage);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("pageSize", pageSize);

        List<Theme> del_themeList = themeService.getDeleteTheme();
        model.addAttribute("del_themeList", del_themeList);
        for (Theme theme : themeList) {
            System.out.println(theme);
        }

        return model;
    }

    /*主题名查重*/
    @RequestMapping("/themeNameCheck")
    public void nameCheck(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String name = request.getParameter("name");
        boolean b = themeService.checkName(name);
        //  System.out.println("输入框的主题名为" + name + " " + b);

        // response.getWriter().write("{\"data\":"+b+"}");*/
        String resultString;
        if (b) {
            response.getOutputStream().print("1");
        } else {
            response.getOutputStream().print(0);
        }


    }

    /*删除主题*/
    @RequestMapping(value = "/deleteT{name}", method = RequestMethod.GET)
    public String deleteU(@PathVariable("name") String name) throws IOException {
        System.out.println("要删除的主题名为" + " " + name);
        themeService.deleteTheme(name);
        return "redirect:/theme";


    }

    /*恢复删除主题*/
    @RequestMapping(value = "/rebackT{name}", method = RequestMethod.GET)
    public String rebackF(@PathVariable("name") String name) throws IOException {
        System.out.println("要恢复的主题名为" + " " + name);
        Theme theme = themeService.getThemeByName(name);
        theme.setStatus(0);
        themeService.updateTheme(theme);
        return "redirect:/theme";


    }


    /*上传主题信息*/
    @RequestMapping(value = "/themeImg", method = RequestMethod.POST)
    public String themeImg(@RequestParam("file") MultipartFile[] files,
                           @RequestParam(value = "inputName", required = false) String inputName,
                           @RequestParam(value = "factory", required = false) String factory,
                           @RequestParam(value = "author", required = false) String author,
                           @RequestParam(value = "description", required = false) String description,
                           HttpServletRequest request
    ) throws IOException {
     /*   boolean b = themeService.checkName(inputName);
        if (b) {
            Theme theme = themeService.getThemeByName(inputName);
            System.err.println("数据库中的主题为" + theme);
            theme.setStatus(0);
            themeService.updateTheme(theme);
        } else {*/


        Factory myFactory = factoryService.getFactoryByID(Integer.valueOf(factory));

        String compressName = files[1].getOriginalFilename();
        int index = compressName.indexOf(".");
        String baseName = compressName.substring(0, index);
        String basePath = "D:" + File.separator + "uploadTheme" + File.separator + baseName;

        //  System.err.println("基本路径为>>>>" + basePath);
        File file1 = new File(basePath);
        if (!file1.exists()) {
            file1.mkdirs();
        }

        //    System.err.println("当前主题信息" + inputName + " " + factory + " " + author + " " + description + " " + " ");



        /*处理文件*/
        int count = 0; //文件数统计
        for (int i = 0; i < files.length; i++) {
            if (!files[i].isEmpty()) {
                try {
                    System.err.println("第{}个文件开始上传" + " " + (i + 1));
                    String fileName = files[i].getOriginalFilename();
                    File filetest = null;
                    if (i == 0) {
                        filetest = new File(basePath + File.separator + fileName);
                    } else {
                        filetest = new File(basePath + File.separator + fileName);
                    }
                    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(filetest));
                    out.write(files[i].getBytes());
                    out.flush();
                    out.close();
                    System.err.println("第{}个文件上传成功" + (i + 1));
                    count++;
                } catch (FileNotFoundException e) {

                    e.printStackTrace();

                } catch (IOException e) {

                    e.printStackTrace();

                } catch (NullPointerException e) {

                    e.printStackTrace();

                }
            }
        }


        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        String uploader = userDetails.getUsername();

        Theme theme = new Theme();
        theme.setName(inputName);
        theme.setFactory(myFactory.getName());
        theme.setAuthor(author);
        theme.setDescription(description);
        theme.setUploader(uploader);

        String imgName = files[0].getOriginalFilename();

        // System.err.println("文件内的名称为" + imgName + " " + compressName);
        String dbPrevirepath = basePath + File.separator + imgName;
        String dbCompresspath = basePath + File.separator + compressName;

        // System.err.println("数据库存放路径为" + dbCompresspath + " " + dbPrevirepath);
        theme.setSchemeFile(dbCompresspath);
        theme.setPreview(dbPrevirepath);
        themeService.addTheme(theme);

        return "redirect:/addTheme";

    }


    /*下载主题*/
    @RequestMapping(value = "/downloadTheme{id}", method = RequestMethod.GET)
    public void downloadTheme(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        String id = request.getParameter("id");
        Theme theme = themeService.getThemeByID(Integer.valueOf(id));
        String name = theme.getName();
        String basepath = theme.getSchemeFile();
        System.err.println("数据库中的存放路径路径为>>>>" + basepath);
      /*  int index=basepath.lastIndexOf("\\");
        String downPath=basepath.substring(0,index);*/
        // System.err.println("下载来源路径为>>>>"+downPath);

        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        // response.setHeader("Content-Disposition", "attachment;filename=" + name + ".itz");
        response.addHeader("Content-Disposition", "attachment;fileName=" + new String((name + ".itz").getBytes("UTF-8"), "iso-8859-1"));

        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(new File(basepath)));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("success");
    }


    /*查看主题详情*/
    @ResponseBody
    @RequestMapping(value = "/detailT", method = RequestMethod.GET)
    public Theme detailT(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        int ID = Integer.valueOf(id);
        Theme theme = themeService.getThemeByID(ID);
        System.err.println(theme);
        return theme;

    }

    /*获取预览图*/
    @RequestMapping(value = "/previewT", method = RequestMethod.GET)
    public void previewT(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        int ID = Integer.valueOf(id);
        Theme theme = themeService.getThemeByID(ID);
        String imgPath = theme.getPreview();
        int index = imgPath.lastIndexOf("\\");
        String imgName = imgPath.substring(index, imgPath.length());
        System.err.println("预览图的名称为" + " " + imgName);

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream");
        response.addHeader(
                "Content-Disposition",
                "attachment; filename=\""
                        + imgName
                        + "\"");

        File file = new File(imgPath);
        FileInputStream fis;
        fis = new FileInputStream(file);

        long size = file.length();
        byte[] temp = new byte[(int) size];
        fis.read(temp, 0, (int) size);
        fis.close();
        byte[] data = temp;
        response.setContentType("image/png");
        OutputStream out = response.getOutputStream();
        data = Base64.encodeBase64(data);
        out.write(data);
        out.flush();
        out.close();


    }

    /*获取厂商列表*/
    @ResponseBody
    @RequestMapping(value = "/getFactoryList", method = RequestMethod.GET)
    public List getFactoryList() {
        List factoryList = factoryService.getAllFactory();
        return factoryList;
    }

    /*获取更新的主题信息*/
    @RequestMapping(value = "/updateT{id}", method = RequestMethod.GET)
    public String updateU(@PathVariable("id") int id, Model model) throws IOException {

        System.err.println("要更新 的主题ID 是" + id);
        Theme theme = themeService.getThemeByID(id);

        int index = theme.getSchemeFile().lastIndexOf("\\");
        String file = theme.getSchemeFile().substring(index + 1);
        theme.setSchemeFile(file);

       /* String imgPath=theme.getPreview();
         int imgindex=imgPath.lastIndexOf("\\");
         String imgfile=imgPath.substring(imgindex+1);
        theme.setPreview(imgfile);
*/
        model.addAttribute(theme);


        return "updateTheme";


    }

    /*保存更新的主题*/
    @RequestMapping(value = "/updateTheme", method = RequestMethod.POST)
    public String updateTheme(@RequestParam("file") MultipartFile[] files,
                              @RequestParam(value = "inputName", required = false) String inputName,
                              @RequestParam(value = "factory", required = false) String factory,
                              @RequestParam(value = "author", required = false) String author,
                              @RequestParam(value = "description", required = false) String description,
                              HttpServletRequest request
    ) throws IOException {
     /*   boolean b = themeService.checkName(inputName);
        if (b) {
            Theme theme = themeService.getThemeByName(inputName);
            System.err.println("数据库中的主题为" + theme);
            theme.setStatus(0);
            themeService.updateTheme(theme);
        } else {*/

        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        String uploader = userDetails.getUsername();

        String ID = request.getParameter("id");
        Theme theme = themeService.getThemeByID(Integer.valueOf(ID));
        theme.setName(inputName);
        theme.setFactory(factory);
        theme.setAuthor(author);
        theme.setDescription(description);
        theme.setUploader(uploader);


        if(files[0].isEmpty()){
            System.out.println("第一个文件为空>>>");
        }else{
            System.out.println("第一个文件不为空、、、、、、、、、");
        }
        if(files[1].isEmpty()){
            System.out.println("第二个文件为空>>>");
        }else{
            System.out.println("第二个文件不为空、、、、、、、、、");
        }



        /* 更新了ITZ包*/
        if (files[0].isEmpty() && (!files[1].isEmpty())) {
            String compressName = files[1].getOriginalFilename();

            int index = compressName.indexOf(".");
            String baseName = compressName.substring(0, index);
            String basePath = "D:" + File.separator + "uploadTheme" + File.separator + baseName;
            String fileName = files[1].getOriginalFilename();
            File filetest = null;
            filetest = new File(basePath + File.separator + fileName);
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(filetest));
            out.write(files[1].getBytes());
            out.flush();
            out.close();

            String dbCompresspath = basePath + File.separator + compressName;

            // System.err.println("数据库存放路径为" + dbCompresspath + " " + dbPrevirepath);
            theme.setSchemeFile(dbCompresspath);

        }

        /*   更换了预览图*/
        if (!files[0].isEmpty() && files[1].isEmpty()) {

            String compressName = theme.getSchemeFile();
            int index = compressName.lastIndexOf(".");
            int begin=compressName.lastIndexOf("\\");
            String baseName = compressName.substring(begin, index);
            String basePath = "D:" + File.separator + "uploadTheme" + File.separator + baseName;

            String fileName = files[0].getOriginalFilename();
            File filetest = null;
            filetest = new File(basePath + File.separator + fileName);
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(filetest));
            out.write(files[1].getBytes());
            out.flush();
            out.close();

            String imgName = files[0].getOriginalFilename();
            String dbPrevirepath = basePath + File.separator + imgName;

            theme.setPreview(dbPrevirepath);

        }


        if (!files[0].isEmpty() && !files[1].isEmpty()) {


            String compressName = files[1].getOriginalFilename();
            int index = compressName.indexOf(".");
            String baseName = compressName.substring(0, index);
            String basePath = "D:" + File.separator + "uploadTheme" + File.separator + baseName;

            //  System.err.println("基本路径为>>>>" + basePath);
            File file1 = new File(basePath);
            if (!file1.exists()) {
                file1.mkdirs();
            }

            //    System.err.println("当前主题信息" + inputName + " " + factory + " " + author + " " + description + " " + " ");



          /*  处理文件*/
            int count = 0; //文件数统计
            for (int i = 0; i < files.length; i++) {
                if (!files[i].isEmpty()) {
                    try {
                        System.err.println("第{}个文件开始上传" + " " + (i + 1));
                        String fileName = files[i].getOriginalFilename();
                        File filetest = null;
                        if (i == 0) {
                            filetest = new File(basePath + File.separator + fileName);
                        } else {
                            filetest = new File(basePath + File.separator + fileName);
                        }
                        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(filetest));
                        out.write(files[i].getBytes());
                        out.flush();
                        out.close();
                        System.err.println("第{}个文件上传成功" + (i + 1));
                        count++;
                    } catch (FileNotFoundException e) {

                        e.printStackTrace();

                    } catch (IOException e) {

                        e.printStackTrace();

                    } catch (NullPointerException e) {

                        e.printStackTrace();

                    }
                }
            }


            String imgName = files[0].getOriginalFilename();

            // System.err.println("文件内的名称为" + imgName + " " + compressName);
            String dbPrevirepath = basePath + File.separator + imgName;
            String dbCompresspath = basePath + File.separator + compressName;

            // System.err.println("数据库存放路径为" + dbCompresspath + " " + dbPrevirepath);
            theme.setSchemeFile(dbCompresspath);
            theme.setPreview(dbPrevirepath);

        }

        themeService.updateTheme(theme);
        return "redirect:/theme";

    }

    /*根据厂商获取所属主题*/
    @ResponseBody
    @RequestMapping("/getThemeByFactory")
    public List<Theme> getThemeByFactory(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String factoryName = request.getParameter("factoryName");
        System.err.println("接收到了获取厂商所属主题的请求》" + "厂商名为" + " " + factoryName);
        List<Theme> themeList = themeService.getThemeByFactory(factoryName);
        for (Theme theme : themeList) {
            System.err.println(factoryName + "拥有的主题有》》" + theme);

        }

        return themeList;

    }

    /*javafx 获取主题缩略图*/
    @RequestMapping("/getPreviewByTheme")
    public void getPreviewByTheme(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String themeName=request.getParameter("themeName");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream");
        response.addHeader(
                "Content-Disposition",
                "attachment; filename=\""
                        + themeName
                        + "\"");
        Theme theme=themeService.getThemeByName(themeName);
        System.err.println("要获取预览图的主题名为》》》"+theme.getPreview());
        File file = new File(theme.getPreview());
        FileInputStream fis;
        fis = new FileInputStream(file);

        long size = file.length();
        byte[] temp = new byte[(int) size];
        fis.read(temp, 0, (int) size);
        fis.close();
        byte[] data = temp;
        response.setContentType("image/png");
        OutputStream out = response.getOutputStream();
       /* data = Base64.encodeBase64(data);*/
        out.write(data);
        out.flush();
        out.close();
    }

     /*javafx下载主题包*/
     @RequestMapping("/downloadByThemeName")
     public void downloadByThemeName(HttpServletRequest request, HttpServletResponse response) throws IOException {

         String themeName = request.getParameter("themeName");
         Theme theme = themeService.getThemeByName(themeName);
         String basepath = theme.getSchemeFile();
         System.err.println("数据库中的存放文件路径为>>>>" + basepath);


         response.setHeader("content-type", "application/octet-stream");
         response.setContentType("application/octet-stream");
         // response.setHeader("Content-Disposition", "attachment;filename=" + name + ".itz");
         response.addHeader("Content-Disposition", "attachment;fileName=" + new String((themeName + ".itz").getBytes("UTF-8"), "iso-8859-1"));
         File itzFile=new File(basepath);
         response.setContentLength((int)itzFile.length()); //对应于HttpURLConnection.getContentLength()

         byte[] buff = new byte[1024];
         BufferedInputStream bis = null;
         OutputStream os = null;
         try {
             os = response.getOutputStream();
             bis = new BufferedInputStream(new FileInputStream(new File(basepath)));
             int i = bis.read(buff);
             while (i != -1) {
                 os.write(buff, 0, buff.length);
                 os.flush();
                 i = bis.read(buff);
             }
         } catch (IOException e) {
             e.printStackTrace();
         } finally {
             if (bis != null) {
                 try {
                     bis.close();
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             }
         }
         System.out.println("success");
     }

     /*根据主题名获取主题*/
     @ResponseBody
     @RequestMapping("/getThemeByName")
     public Theme getThemeByName(HttpServletRequest request, HttpServletResponse response) throws IOException {

         String themeName = request.getParameter("themeName");
         Theme theme = themeService.getThemeByName(themeName);
         return theme;
     }


}
